let cloud = wx.cloud
App({
    getRandomAd(isOnLoad,e){
        let that = e||this
        that.getRandomAd = function(a){
          if (getApp().globalData.selfAd.length==0){
            return
          }
            if(getApp().globalData.onload == true){ 
                if(a !== undefined){
                    console.log(a)
                    that.setData({
                        ad: getApp().globalData.selfAd[parseInt(getApp().globalData.selfAd.length*Math.random())]
                    });
                } else {
                    
                }
            } else {
                if(a !== undefined){
                } else {
                    that.setData({
                        ad: getApp().globalData.selfAd[parseInt(getApp().globalData.selfAd.length*Math.random())]
                    });
                }   
            }
        }
    },
    chaping(){
      if (!this.globalData.chaping) { return }
      if (!wx.getStorageSync('chapingShow')) { return }
      console.log(2)
      if (new Date().getTime()-wx.getStorageSync('jiange')<15000) { return }
        let that = this
        let interstitialAd = null
        if (wx.createInterstitialAd) {
            interstitialAd = wx.createInterstitialAd({
              adUnitId: that.globalData.adTest.filter(item=>{
                  return item.type == 'chaping'
              })[0].id
            })
            interstitialAd.onLoad(() => {})
            interstitialAd.onError((err) => {})
            interstitialAd.onClose(() => {})
        }
        if (interstitialAd) {
            interstitialAd.show().catch((err) => {
                wx.setStorageSync('chapingShow', true)
                console.error(err)
            })
            wx.setStorageSync('chapingShow', false)
        }
    },
    checkMsg(e){
        console.log(e)
        wx.showLoading({
          title: '请稍等...',
        })
        return new Promise((resolve,reject)=>{
            cloud.callFunction({
                name:'checkMsg',
                data: {data:e},
                success(res){
                    resolve(res)
                    wx.hideLoading()
                },
                fail(res){
                    console.log(res)
                    resolve(undefined)
                    wx.hideLoading()
                }
            })
        })
    },
    checkImg(e){
        console.log(e)
        let that = this
        wx.showLoading({
          title: '请稍等...',
        })
        return new Promise((resolve,reject)=>{
            wx.getFileSystemManager().readFile({
                filePath:e,
                encoding:'base64',
                success(res){
                    cloud.callFunction({
                        name:'checkImg',
                        data: {data:res.data},
                        success(res){
                            resolve(res)
                            wx.hideLoading()
                        },
                        fail(res){
                            console.log(res)
                            resolve(undefined)
                            wx.hideLoading()
                        }
                    })
                },
                fail(res){
                    resolve(undefined)
                },
                complete(){
                    wx.hideLoading()
                }
            })
        })
       
    },
    getUser(callback){
        cloud.database().collection('user').where({
            openId: wx.getStorageSync('openId') // 填入当前用户 openid
        })
        .get()
        .then((e)=>{
            console.log(e)
            if(e.data.length != 0){
              let date = new Date()
              wx.setStorageSync('userInfo', e.data[0].userInfo)
              if (e.data[0].userInfo.date != (date.getFullYear() + '-' + date.getMonth() + '-' + date.getDate())){
                
                cloud.database().collection('user')
                  .where({
                    openId: wx.getStorageSync('openId')
                  })
                  .update({
                    // data 传入需要局部更新的数据
                    data: {
                      userInfo:{
                        date: date.getFullYear() + '-' + date.getMonth() + '-' + date.getDate(),
                        count:wx.getStorageSync('count')?wx.getStorageSync('count').count:1,
                        zhuli:wx.getStorageSync('count')?wx.getStorageSync('count').zhuli:1
                      }
                    }
                  })
                  .then((res)=>{
                    wx.setStorageSync('loginTime', date.getFullYear() + '-' + date.getMonth() + '-' + date.getDate())
                    e.data[0].userInfo.date = date.getFullYear() + '-' + date.getMonth() + '-' + date.getDate()
                    e.data[0].userInfo.count = wx.getStorageSync('count')?wx.getStorageSync('count').count:1
                    e.data[0].userInfo.zhuli = wx.getStorageSync('count')?wx.getStorageSync('count').zhuli:1
                    wx.setStorageSync('userInfo', e.data[0].userInfo)
                    callback()
                  })
              }
            }
            callback()
        })
        .catch((e)=>{
            wx.hideLoading()
        })
    },
    WX_LOGIN(callback){
        let that = this
        let date = new Date()
        if (wx.getStorageSync('loginTime') == (date.getFullYear() + '-' + date.getMonth() + '-' + date.getDate())&&wx.getStorageSync('userInfo')){
            callback()
            return
        }
        cloud.database().collection('count')
        .get()
        .then(e=>{
            wx.setStorageSync('count', e.data[0])
        })
        wx.showLoading({
          title: '请稍等...',
          mask:true
        })
        if(wx.getStorageSync('openId')){
            this.getUser(callback)
            return
        } else{
            cloud.callFunction({
                name:'openapi',
                success(res){
                    console.log(res)
                    wx.setStorageSync('openId', res.result.event.userInfo.openId)
                    that.getUser(callback)
                },
                fail(res){
                    console.log(res)
                    wx.hideLoading()
                }
            })
        }
        
    },
    onLaunch: function() {
      if (wx.getStorageSync('date') != new Date().getDate()){
        wx.setStorageSync('date', new Date().getDate())
        wx.setStorageSync('chapingShow', true)
        wx.setStorageSync('jiange', new Date().getTime())
      } else {
        wx.setStorageSync('jiange', new Date().getTime())
      }
        
        var t = this;
        wx.cloud.init();
        wx.cloud.database().collection('ad').get().then(res => {
            if(res.data.length == 1){
                t.globalData.selfAd = res.data[0].ad
                t.globalData.adTest = res.data[0].adTest
                t.globalData.test = res.data[0].test
                t.globalData.chaping = res.data[0].chaping
                t.globalData.onload = res.data[0].onload
            }
        })
        var e = wx.getStorageSync("logs") || [];
        e.unshift(Date.now()), wx.setStorageSync("logs", e);
        var s = this;
        this.globalData.myDevice = wx.getSystemInfoSync();
        for (var a = 0; a < 156; a++) this.globalData.imgUrl[a] = "https://ishare20.net/emotion/" + (a + 1) + ".png";
        wx.login({
            success: function(t) {}
        }), wx.getSetting({
            success: function(e) {
                e.authSetting["scope.userInfo"] && wx.getUserInfo({
                    success: function(e) {
                        t.globalData.userInfo = e.userInfo, t.userInfoReadyCallback && t.userInfoReadyCallback(e);
                    }
                });
            }
        }), wx.request({
            url: "https://ishare20.net/gifmaker/appset.json",
            headers: {
                "Content-Type": "application/json"
            },
            success: function(t) {
                s.globalData.appset = t.data;
            }
        }), wx.request({
            url: "https://ishare20.net/gifmaker/wxminiset.json",
            headers: {
                "Content-Type": "application/json"
            },
            success: function(t) {
                s.globalData.wxminiset = t.data;
            }
        });
    },
    globalData: {
        userInfo: null,
        myDevice: null,
        imgUrl: [],
        ad: {},
        apiUrl: "https://ishare20.net/textToPic",
        appset: {},
        appid: "wxb8dcb03dab37e2f8",
        wxminiset: [],
        selfAd:[],
        adTest:[],
        test:0,
        onload:true,
        chaping:false,
        bgThemeColor:'#009688'
    }
});